package com.dd.admin.business.pay.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.dd.admin.business.card.entity.Card;
import com.dd.admin.business.card.service.CardService;
import com.dd.admin.business.detailServer.entity.SellDetailServer;
import com.dd.admin.business.detailServer.service.SellDetailServerService;
import com.dd.admin.business.memberCard.domain.MemberCardVo;
import com.dd.admin.business.memberCard.entity.MemberCard;
import com.dd.admin.business.memberCard.service.MemberCardService;
import com.dd.admin.business.pay.domain.*;
import com.dd.admin.business.pay.service.AddSellDetailService;
import com.dd.admin.business.pay.service.PayService;
import com.dd.admin.business.sell.entity.Sell;
import com.dd.admin.business.sell.service.SellService;
import com.dd.admin.business.sellDetail.entity.SellDetail;
import com.dd.admin.business.sellDetail.service.SellDetailService;
import com.dd.admin.business.sellPay.entity.Sellpay;
import com.dd.admin.business.sellPay.service.SellpayService;
import com.dd.admin.business.server.domain.ServerVo;
import com.dd.admin.common.exception.ApiException;
import com.dd.admin.common.utils.BigDecimalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

import static com.dd.admin.business.pay.enmus.CashierExceptionEnum.CARD_AMOUNT_CHANGE;
import static com.dd.admin.business.pay.enmus.PayConst.PRODUCT_TYPE_CHARGED_CARD;

/**
 * MemberCardRenewServiceImpl 类，实现了 AddSellDetailService 接口，用于处理会员卡续卡的业务逻辑
 */
@Service
public class SellDetailChargedCard implements AddSellDetailService {

    @Autowired
    private MemberCardService memberCardService; // 用于操作会员卡相关业务
    @Autowired
    private SellDetailService sellDetailService; // 处理销售详情的服务
    @Autowired
    private PayService payService; // 支付相关的服务
    @Autowired
    private SellpayService sellpayService; // 销售支付的服务
    @Autowired
    private SellDetailServerService sellDetailServerService;
    @Autowired
    private CardService cardService;
    /**
     * 处理添加销售详情的方法
     *
     * @param sell    销售实体
     * @param baseSell 基础销售数据
     */
    @Override
    public void addSellDetail(Sell sell, BaseSell baseSell) {
        // 将基础销售数据转换为 ChargedCardSell 类型
        ChargedCardSell chargedCardSell = (ChargedCardSell) baseSell;
        // 通过会员卡服务根据会员卡号获取会员信息
        MemberCard memberHistoryCard = memberCardService.getById(chargedCardSell.getMemberCardId());
        // 执行会员卡续卡的核心逻辑，并获取续卡后的会员信息
        MemberCard chargedMemberCard = chargedMemberCard(chargedCardSell, memberHistoryCard);

        // 生成销售细单
        SellDetail sellDetail = createSellDetail(chargedCardSell, sell, chargedMemberCard);

        // 通过销售支付服务添加销售支付列表
        sellpayService.addSellPayList(chargedCardSell.getSellPayList(), sell.getSellId());

        // 通过支付服务设置销售的额外信息
        payService.setSellExtraInfo(sell.getSellId(), chargedMemberCard, BigDecimal.ZERO, BigDecimal.ZERO);
    }

    /**
     * 执行会员卡续卡的核心逻辑
     *
     * @param chargedCardSell   构建卡销售数据
     * @param memberHistoryCard 原会员卡信息
     * @return 续卡后的会员卡信息
     */
    MemberCard chargedMemberCard(ChargedCardSell chargedCardSell, MemberCard memberHistoryCard) {
        // 获取原会员卡卡内金额
        BigDecimal memberBeforeAmount = memberHistoryCard.getAmount();
        // 获取原会员卡赠送金额
        BigDecimal memberBeforeGiveAmount = memberHistoryCard.getGiveAmount();

        // 从构建卡销售数据中获取续卡表单
        ChargedCardForm chargedCardForm = chargedCardSell.getChargedCardForm();
        // 获取续卡充值金额
        BigDecimal chargedAmount = chargedCardForm.getChargedCardAmount();
        // 获取续卡赠送金额
        BigDecimal chargedGiveAmount = chargedCardForm.getChargedGiveAmount();

        // 计算并设置续卡后的卡内金额
        memberHistoryCard.setAmount(BigDecimalUtil.add(memberBeforeAmount, chargedAmount));
        // 计算并设置续卡后的赠送金额
        memberHistoryCard.setGiveAmount(BigDecimalUtil.add(memberBeforeGiveAmount, chargedGiveAmount));

        // 更新会员卡信息
        Boolean updated = memberCardService.updateById(memberHistoryCard);
        // 如果更新失败，抛出异常
        if (!updated) {
            throw new ApiException(CARD_AMOUNT_CHANGE);
        }

        return memberHistoryCard;
    }

    /**
     * 创建销售细单
     *
     * @param chargedCardSell 构建卡销售数据
     * @param sell          销售实体
     * @param memberCard    会员卡信息
     * @return 生成的销售细单
     */
    SellDetail createSellDetail(ChargedCardSell chargedCardSell, Sell sell, MemberCard memberCard) {
        // 从构建卡销售数据中获取续卡表单
        ChargedCardForm chargedCardForm = chargedCardSell.getChargedCardForm();
        // 创建新的销售细单对象
        SellDetail sellDetail = new SellDetail();
        // 设置销售细单的销售 ID
        sellDetail.setSellId(sell.getSellId());
        // 设置销售细单的销售类型
        sellDetail.setSellType(sell.getSellType());
        // 设置销售细单的会员 ID
        sellDetail.setMemberId(sell.getMemberId());

        // 设置销售细单的产品类型为续卡
        sellDetail.setProductType(PRODUCT_TYPE_CHARGED_CARD);
        // 设置销售细单的卡 ID
        sellDetail.setCardId(chargedCardForm.getCardId());
        // 设置销售细单的卡名称
        sellDetail.setCardName(chargedCardForm.getCardName());
        // 设置销售细单的续卡金额
        sellDetail.setAmount(chargedCardForm.getChargedCardAmount());
        // 设置销售细单的续卡赠送金额
        sellDetail.setGiveAmount(chargedCardForm.getChargedGiveAmount());
        // 设置销售细单的实际金额
        sellDetail.setRealAmount(chargedCardForm.getChargedCardAmount());
        sellDetail.setTotalRealAmount(chargedCardForm.getTotalRealAmount());
        // 设置销售细单的会员卡号
        sellDetail.setMemberCardId(memberCard.getMemberCardId());

        // 保存销售细单
        sellDetailService.save(sellDetail);


        Card card = cardService.getById(chargedCardForm.getCardId());


        //该条目有服务人员
        List<ServerVo> serverList = chargedCardForm.getServerList();
        if (CollectionUtil.isNotEmpty(serverList)) {
            //如果是固定金额 固定金额除以人数 获取固定金额
            //如果是比例 计算出比例后提成 获取固定金额
            //业绩和提成均平均分
            //总提成
            BigDecimal totalPushMoney = BigDecimal.ZERO;
            //总业绩 为订单实付金额
            BigDecimal totalGradeMoney = sellDetail.getTotalRealAmount();
            //固定金额的话
            //按比例
            if (card.getCardPushPercent() != null) {
                //提成额 先转换为百分数
                BigDecimal pushPercent = BigDecimalUtil.div(card.getCardPushPercent(), new BigDecimal("100"));
                //折后价*百分数
                totalPushMoney = BigDecimalUtil.mul(totalGradeMoney, pushPercent);
            }


            //平均分
            BigDecimal pushMoney = BigDecimalUtil.div(totalPushMoney, new BigDecimal(serverList.size()));
            BigDecimal gradeMoney = BigDecimalUtil.div(totalGradeMoney, new BigDecimal(serverList.size()));


            //设置服务人员
            serverList.stream().forEach(server -> {
                SellDetailServer sellDetailServer = new SellDetailServer();
                sellDetailServer.setSellId(sell.getSellId());
                sellDetailServer.setSellDetailId(sellDetail.getSellDetailId());
                sellDetailServer.setServerId(server.getServerId());
                sellDetailServer.setServerName(server.getServerName());
                sellDetailServer.setServerPushMoney(pushMoney);
                sellDetailServer.setServerGrade(gradeMoney);
                sellDetailServerService.save(sellDetailServer);
            });
        }
        return sellDetail;
    }
}
